# -*- coding:utf-8 -*-


import time
import json
import config
import pymongo
from scrapy import Spider
from scrapy.http import Request


class BittrexExchange(Spider):
    name = 'bittrex'

    handle_httpstatus_list = [429]

    def __init__(self, name=None, **kwargs):
        super(BittrexExchange, self).__init__(name, **kwargs)

        # 连接mongodb
        client = pymongo.MongoClient('47.254.26.182', 27017)
        # client = pymongo.MongoClient('localhost', 27017)
        self.db = client.bt_news

    def start_requests(self):
        url = 'https://bittrex.com/api/v1.1/public/getmarketsummaries'

        yield Request(
            url=url,
            dont_filter=True,
            headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
            },
            meta={

            },
            callback=self.exchange_info
        )

    def exchange_info(self, response):
        # 获取json中的数据，对应交易所信息
        body = json.loads(response.body)

        result = body.get('result')
        for info in result:
            # 交易对
            exchange_pair = info.get('MarketName').split('-')
            pair_name = str(exchange_pair[0]).upper()
            variual_pair = str(exchange_pair[1]).upper()

            # 交易所名称
            exchange_name = 'bittrex'

            # 买家
            buy = info.get('Ask')

            # 卖价
            sell = info.get('Bid')

            # 最高价
            high = info.get('High')

            # 最低价
            low = info.get('Low')

            # 成交量
            vol = info.get('Volume')

            # 时间
            okcoin_time = info.get('TimeStamp')

            # 最新成交价
            last = info.get('Last')

            # 入库mongo
            data = {
                'exchange_name': exchange_name,
                'variual_coin_name': pair_name,
                'variual_pair': variual_pair,
                # 'market_value': market_value,
                'buy': buy,
                'sell': sell,
                'high': high,
                'low': low,
                'last': last,
                'vol': vol,
                'time': okcoin_time,
                # 'roportion': roportion,
                # 'hasklin': hasklin,
                # 'change1d': change1d,
                'updatetime': time.localtime()
            }

            # pairs = [pair_name, variual_pair]
            # for pair in pairs:
            #     display_name = pair
            #
            #     data_pair = {
            #         'display_name': display_name
            #     }
            #
            #     self.db.bt_virtual_coin.update_one(
            #         {'display_name': display_name},
            #         {'$set': data_pair}, upsert=True)

            if response.status == 200:
                # 入库mongo
                self.db.bt_coin.update_one({'exchange_name': exchange_name, 'variual_coin_name': pair_name, 'variual_pair': variual_pair},
                                           {'$set': data}, upsert=True)

        url = response.url
        yield Request(
            url=url,
            dont_filter=True,
            headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
            },
            meta={

            },
            callback=self.exchange_info
        )


'''
每三秒更新mongo中的数据
'''